

package com.code.ape.codeape.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.code.ape.codeape.admin.api.entity.SysDept;
import com.code.ape.codeape.admin.api.entity.SysDeptRelation;
import com.code.ape.codeape.admin.mapper.SysDeptRelationMapper;
import com.code.ape.codeape.admin.service.SysDeptRelationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 公众号：码猿技术专栏   版权：不才陈某所署，侵权必究
 * @since 2019/2/1
 */
@Service
@RequiredArgsConstructor
public class SysDeptRelationServiceImpl extends ServiceImpl<SysDeptRelationMapper, SysDeptRelation>
		implements SysDeptRelationService {

	private final SysDeptRelationMapper sysDeptRelationMapper;

	/**
	 * 维护部门关系
	 * @param sysDept 部门
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveDeptRelation(SysDept sysDept) {
		//step1 如果选择了子级部门，则新增关联关系
		if (Objects.nonNull(sysDept.getParentId())&&!Objects.equals(sysDept.getParentId(),0L)){
			// 自己也要维护到关系表中
			SysDeptRelation own = new SysDeptRelation();
			own.setDescendant(sysDept.getDeptId());
			own.setAncestor(sysDept.getParentId());
			sysDeptRelationMapper.insert(own);
		}
	}

	/**
	 * 通过ID删除部门关系
	 * @param id
	 */
	@Override
	public void removeDeptRelationById(Long id) {
		baseMapper.deleteDeptRelationsById(id);
	}

	/**
	 * 更新部门关系
	 * @param relation
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateDeptRelation(SysDeptRelation relation) {
		baseMapper.deleteDeptRelations(relation);
		baseMapper.insertDeptRelations(relation);
	}

}
